var express = require("express");
var path = require("path");

var app = express();
var artTemplate = require("express-art-template");

app.use(express.urlencoded({ extended: false }));

app.engine("html", artTemplate);

app.set("views", path.join(__dirname, "views"));
var mongoose = require("mongoose");
//md5
var md5 = require("md5");

// session
var session = require('express-session');
//中间件连接数据库
var MongoStore = require('connect-mongo')(session);
//闪存模块
var flash = require('connect-flash');

app.use(flash());

// session的配置
app.use(session({
  secret: 'myuser',
  rolling: true,
  cookie:{
      maxAge: 1000*60*60
  },
  store:new MongoStore({
      url: 'mongodb://127.0.0.1:27017/sessionLX'
  }),
}));

mongoose.connect(
  "mongodb://127.0.0.1:27017/sessionLX",
  {
    useNewUrlParser: true,
    useUnifiedTopology: true
  },
  function(err) {
    if (err) {
      console.log(err);
      console.log("数据库连接失败");
    } else {
      console.log("数据库连接成功");
    }
  }
);

var User = mongoose.model("user", {
  username: String,
  password: String
});

var Message = mongoose.model("mes", {
  time1: String,
  time2: String,
  host: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "user"
  },
  txt: String,
  reply: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "rep"
    }
  ]
});

var Reply = mongoose.model("rep", {
  time1: String,
  time2: String,
  host: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "user"
  },
  txt: String
});

// 注册跳转
app.get("/registbtn", (req, res) => {
  res.render("register.html",{
    error: req.flash('error').toString()
});
});
//登录跳转
app.get("/loginbtn", (req, res) => {
  res.render("login.html",{
    error: req.flash('error').toString()
});
});

//注册
app.post("/register", (req, res) => {
  User.findOne({ username: req.body.username }, (err, data) => {
    if (data) {
      // res.send("账号已存在");
      req.flash('error', '账号已存在');
      res.redirect('/registbtn');
    } else {
      req.body.password = md5(req.body.password);

      var user = new User(req.body);
      user.save(err => {
        res.redirect("/");
      });
    }
  });
});

//登录
app.post("/login", (req, res) => {
  User.findOne({ username: req.body.username }, (err, user) => {
    if (user) {
      if (md5(req.body.password) == user.password) {
        req.session.user = user;
        res.redirect("/");
      } else {
        // res.send("密码错误");
        req.flash('error', '密码错误');
       res.redirect('/loginbtn');
      }
    } else {
      // res.send("账号不存在");
      req.flash('error', '账号不存在');
      res.redirect('/loginbtn');
    }
  });
});

//提交信息
app.get("/mess", function(req, res) {
  var condition = {};
  condition.username = req.session.user.username;
  console.log(condition.username);
  User.find(condition, function(err, data) {
    if (err) {
      console.log("查询失败");
    } else {
      var txt = req.query.txt;
      var now = new Date();
      var time1 =now.getFullYear() +" " +(now.getMonth() +1) +
        " " +
        now.getDate() +
        " ";
      var time2 =
        now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
      var host = data[0]._id;
      var ddaa = { time1, time2, host, txt };
      var stu = new Message(ddaa);
      // 向数据库插入一条数据
      stu.save(function(err) {
        if (err) {
          console.log(err);
          console.log("保存失败");
        } else {
          console.log("保存成功");
        }
      });
    }
  });
  res.redirect("/");
});

//回复信息
app.get("/Replay/:aid", function(req, res) {
  var condition = {};
  condition.username = req.session.user.username;
  User.find(condition, (err, data) => {
    if (err) {
      console.log("查询失败");
    } else {
      var host = data[0]._id;
      var txt = req.query.txt;
      var now = new Date();
      var time1 =
        now.getFullYear() +
        " " +
        (now.getMonth() +
        1) +
        " " +
        now.getDate() +
        " ";
      var time2 =now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
      var reply = req.params.aid;
      var ddaa = { time1, time2, host, txt };
      var ply = new Reply(ddaa);
      // 向数据库插入一条数据
      ply.save(function(err, rea) {
        if (err) {
          console.log(err);
          console.log("保存失败");
        } else {
          console.log(rea);
          var aa = rea._id;
          Message.updateOne(
            {
              _id: reply
            },
            {
              $push: {
                reply: mongoose.mongo.ObjectId(aa)
              }
            },
            function(err) {
              if (err) {
                console.log(err);
                console.log("更新失败");
              } else {
                console.log("更新成功");
              }
            }
          );
          console.log("保存成功");
        }
      });
    }
  });

  res.redirect("/");
});

//退出
app.get('/logout', (req, res)=>{

  delete req.session.user;
  res.redirect('/');
})


function gettime(num) {
  var nowTime = new Date();
  var targetTime = new Date(num);
  var offsetTime = (nowTime.getTime() - targetTime.getTime()) / 1000;
  var minute = 60,
    hour = minute * 60,
    day = hour * 24;
  var days = Math.floor(offsetTime / day);
  var hours = Math.floor((offsetTime % day) / hour);
  var minutes = Math.floor(((offsetTime % day) % hour) / minute);
  var seconds = offsetTime % minute;

  var str=''
  if (offsetTime<minute) {
      str='刚刚发布'
  }else if (offsetTime<hour) {
      str=minutes+'分钟前'
  }else if (offsetTime<day) {
      str=hours+'小时前'
  }else {
      str=days+'天前'
  }
console.log(str);
  return str
}


// 显示信息
app.get("/", function(req, res) {
  Message.find()
    .populate({path:"reply",populate:'host'})
    .exec(function(err, content) {



      content.forEach((stu)=>{
        // console.log(msg);
        stu.time2 = gettime(stu.time1+stu.time2);
        // 回复的事件
        stu.reply.forEach(ply=>{
          ply.time2 = gettime(ply.time1+ply.time2);
        });
    });

console.log(content);
      
      

      res.render("index.html", { content:content,
        user: req.session.user});
    });
});


app.listen(5555, function() {
  console.log("服务器启动...");
});
